/*
 *  Copyright 2007 Blandware (http://www.blandware.com)
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.blandware.atleap.webapp.action.core.backup;

import org.apache.struts.action.*;
import org.apache.struts.upload.FormFile;
import org.springframework.dao.DataAccessException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blandware.atleap.webapp.form.core.UploadBackupForm;
import com.blandware.atleap.webapp.util.core.GlobalProperties;
import com.blandware.atleap.service.core.BackupManager;
import com.blandware.atleap.common.Constants;

import java.io.InputStream;

/**
 * Takes data uploaded by user and tries to restore DB state from this data.
 * <p><a href="UploadBackupAction.java.html"><i>View source</i></a></p>
 *
 * @author Roman Puchkovskiy <a href="mailto:roman.puchkovskiy@blandware.com">
 *         &lt;roman.puchkovskiy@blandware.com&gt;</a>
 * @version $Revision: 1.1 $ $Date: 2007/06/06 13:43:02 $
 * @struts.action path="/core/backup/upload"
 * name="uploadBackupForm"
 * scope="request"
 * input="inputForward"
 * validate="true"
 * roles="core-backup-upload, core-backup-restore"
 * @struts.action-forward name="listArchives"
 * path="/core/backup/list.do"
 * redirect="true"
 * @struts.action-forward name="inputForward"
 * path="/core/backup/callUpload.do"
 * @struts.action-forward name="unsatisfiable"
 * path="/core/backup/list.do"
 */
public class UploadBackupAction extends RestoreActionSupport {
    /**
     * @param mapping  The ActionMapping used to select this instance
     * @param form     The optional ActionForm bean for this request (if any)
     * @param request  The HTTP request we are proceeding
     * @param response The HTTP response we are creating
     * @return an ActionForward instance describing where and how
     *         control should be forwarded, or null if response
     *         has already been completed
     */
    public ActionForward execute(ActionMapping mapping, ActionForm form,
                                 HttpServletRequest request, HttpServletResponse response) throws Exception {

        GlobalProperties globalProperties = GlobalProperties.getInstance(request.getSession().getServletContext());
        boolean enabled = "true".equalsIgnoreCase(globalProperties.getString("dbbackup.upload", "false"));

        // if this feature is disabled in build properties, deny access
        if (!enabled) {
			response.sendError(HttpServletResponse.SC_FORBIDDEN);
			return null;
        }

        if (isCancelled(request)) {
            resetToken(request);
            return mapping.findForward("listArchives");
		}

		UploadBackupForm uploadBackupForm = (UploadBackupForm) form;

		FormFile file = uploadBackupForm.getFile();
		if ( file == null || file.getFileName() == null || file.getFileName().trim().length() == 0 || file.getFileSize() == 0 ) {
			ActionMessages errors = new ActionMessages();
			errors.add("backupNoData", new ActionMessage("core.backup.errors.noData"));
			saveErrors(request, errors);
			saveToken(request);
			return mapping.getInputForward();
		}

        InputStream inputStream = file.getInputStream();
        BackupManager backupManager = (BackupManager) getBean(Constants.BACKUP_MANAGER_BEAN);

        try {
            backupManager.restore(inputStream, Boolean.TRUE);
        } catch (DataAccessException ex) {
            ActionMessages errors = new ActionMessages();
            errors.add("cannotRestore", new ActionMessage("core.backup.errors.cannotRestore"));
            saveErrors(request, errors);
            return mapping.findForward("listArchives");
        }

        doAfterRestore(request);

        ActionMessages messages = new ActionMessages();
        messages.add("success", new ActionMessage("core.backup.messages.success"));
        saveMessages(request, messages);

        return mapping.findForward("listArchives");
    }
}
